package com.entitymapper.field.impl;

import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;

import com.entitymapper.EntityMapperException;
import com.entitymapper.driver.Format;
import com.entitymapper.driver.impl.RFIDFormat;
import com.entitymapper.field.AbstractResultSet;
import com.entitymapper.xml.rfid.Configure;

/**
 * 调用驱动，读写数据操作
 * @author hhf
 */
public class RFIDResultSet extends AbstractResultSet{
	
	private static final Logger log = Logger.getLogger(RFIDResultSet.class);
	public RFIDResultSet(Class<?> entityType) {
		super(entityType);
	}
	
	/**
	 * 通过实体对象的属性名进行读操作
	 * @param fieldName 实体对象的属性名
	 * @throws EntityMapperException
	 */
	public String readValue(String fieldName){
		String value = null;
		//RFIDFormat format = (RFIDFormat) CheckRFIDMapping.chectFieldName(entityType,fieldName);
		value = driver.read(readfieldAttribute(fieldName,entityType));
		return value;
	}

	/**
	 * 通过实体对象的属性名与实体对象进行写操作
	 * @param fieldName 实体对象的属性名
	 * @param object 实体对象
	 * @throws EntityMapperException 
	 */
	public void writeValue(String fieldName, Object object){
		//RFIDFormat format = (RFIDFormat) CheckRFIDMapping.chectFieldName(entityType,fieldName);
		driver.write(readfieldAttribute(fieldName,entityType), object.toString());
	}
	
	private Format readfieldAttribute(String fieldName,Class<?> entityType) {
		RFIDFormat format = new RFIDFormat();
		Map<String,List<String>> map;
		List<String> fields;
		int count = 0;
		int start = 0;
		try {
			map = Configure.getConfigureMap().get(entityType.getSimpleName());
		} catch (Exception e) {
			log.error(e);
			throw new EntityMapperException("the "+entityType.getName()+" has not Annotation!",e);
		}
		try {
			fields = map.get(fieldName);
		} catch (Exception e) {
			log.error(e);
			throw new EntityMapperException("the "+fieldName+" has not Annotation!",e);
		}
		try {
			count = Integer.parseInt(fields.get(0));
			start = Integer.parseInt(fields.get(1));
		}catch(NumberFormatException e) {
			log.error(e);
			throw new EntityMapperException("the "+fieldName+" transport has NumberFormatException!",e);
		}
		format.setAreaCount(count);
		format.setAreaStart(start);
		return format;
	}
}
